package cm.cool.web.service.admin;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cm.cool.web.bean.Admin;
import cm.cool.web.bean.AdminRecord;
import cm.cool.web.data.LoginMapper;
import cm.cool.web.util.cookie.CookieOp;
import cm.cool.web.util.date.TimeUtil;
import cm.cool.web.util.respon.R;
import cm.cool.web.util.respon.ResultEncoding;
import cm.cool.web.util.security.MD5;
import cm.cool.web.util.tokencache.TokenCacheMap;
import cm.cool.web.util.tokencache.TokenUtil;

@Service
public class LoginService {
	
	@Autowired
	LoginMapper loginMapper;
	
	@Value("${cookie.name}")
	private String cookieName;
	
	@Autowired
	private AdminRecordService adminRecordService;
	
	/**
	 * 管理员登录
	 * @param user
	 * @return
	 */
	public R login(Admin user,HttpServletResponse response){
		
		R r=new R();
		//数据验证
		if(R.isNull(user.getAccount()) ||  R.isNull(user.getAccount())){
			r.setData("用户名或密码为空");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}
		
		//请求数据
		Admin resultUser=null;
		
		//密码加密
		user.setPassword(MD5.EncoderByMd5(user.getPassword()));
		
		try {
			resultUser=loginMapper.login(user);
			
		} catch (Exception e) {
			System.out.println("登录异常=============="+e.getMessage());
		}
		
		if(resultUser==null){
			r.setMsg("账号或者密码错误");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}
		
		//验证登录是否被禁用
		if(resultUser.getState().equals("0")){
			//验证帐号是否需要被禁用
			r.setMsg("账号被禁用");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}	
		
		//验证登录是否成功
		if(!resultUser.getPassword().equals(user.getPassword())){
			//验证帐号是否需要被禁用
			chekeAccount(user.getAccount());
			r.setMsg("账号或者密码错误");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}
		
		
		//登錄成功 生成token信息
		String token=resultUser.getId()+"_"+UUID.randomUUID()+"_"+resultUser.getAccount()+"_"+TimeUtil.getSecond();
		
		//删除禁用信息
		TokenCacheMap.deleteLockList(user.getAccount());
		
		//將token信息存入到內存当中
		TokenCacheMap.addTokenList(resultUser.getId(), token);
		
		//判断获取的cookie名称 
		if(cookieName==null || cookieName.equals("")){
			cookieName="securityName";
		}
		
		//将token存入到cookie中
		if(CookieOp.setCookie(response, cookieName, token)){
			r.setMsg("登录成功");
		}
		
		//添加登录记录
		AdminRecord adminRecord=new AdminRecord();
		adminRecord.setId(UUID.randomUUID().toString());
		adminRecord.setOperation("登录");
		adminRecord.setUserId(resultUser.getId());
		adminRecordService.insertRecord(adminRecord);
		return r;
	}
	
	
	/**
	 * 登出系统
	 * @param user
	 * @param response
	 * @return
	 */
	public R loginOut(Admin user ,HttpServletRequest request){
		R r=new R();
		
		try {
			 String tokenValue=CookieOp.getCookie(request, cookieName);
			 String uid=TokenUtil.getAdminId(tokenValue);
			 if(R.isNull(uid)){
				 r.setMsg("获取系统参数失败，登出错误");
				 r.setCode(ResultEncoding.R_PARAMETER);
				 return r;
			 }
			 TokenCacheMap.deleteTokenList(uid);
			 r.setMsg("退出成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return r;
	}
	
	/**
	 * 检验帐号禁用问题
	 */
	public  void chekeAccount(String account){
		
		try {
			//拿到数据
			String lockText=TokenCacheMap.getLockList(account);
			
			//测试数据是否为空
			if(lockText==null || lockText.equals("")){//当错误次数为空的时候添加第一次错误记录
				TokenCacheMap.addLockList(account, TimeUtil.getSecond()+"_1");
				return;
			}
			
			//测试数据格式是否正确
			String[] lockText_s=lockText.split("_");
			if(lockText_s.length!=2){
				TokenCacheMap.addLockList(account, TimeUtil.getSecond()+"_1");
				return;
			}
			
			//判断登录实现
			if(Integer.parseInt(lockText_s[1])<5  && TimeUtil.getSecond()-Long.valueOf(lockText_s[0])>1800){
				TokenCacheMap.addLockList(account, TimeUtil.getSecond()+"_1");
				return;
			}
			//禁掉用户
			if(Integer.parseInt(lockText_s[1])>=4){
				loginMapper.updateState("0",account);
				return;
			}
			
			String lock_text=TimeUtil.getSecond()+"_"+(Integer.parseInt(lockText_s[1])+1);
			TokenCacheMap.addLockList(account, lock_text);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
	}

	/**
	 * 验证是否有权利修改密码
	 * @param user
	 * @param request
	 * @return
	 */
	public String checkAcount(Admin user, HttpServletRequest request) {
		
		String tokenValue=CookieOp.getCookie(request, cookieName);
		if(tokenValue==null || tokenValue.equals("")){
			return "0";
		}
		
		if(user.getId().equals(tokenValue.split("_")[0])){
			return "1";
		}
		
		return "0";
	}
	
	/**
	 * 启用指定用户
	 * @param id
	 * @return
	 */
	public String upAdmin(String account) {
		try {
			//删除禁用信息
			TokenCacheMap.deleteLockList(account);
			loginMapper.updateState("1",account);
			return "启用成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	public R updatePasswords(Admin admin,String password_s,HttpServletRequest request){
		R r=new R();
		
		try {
			String tokenValue=CookieOp.getCookie(request, cookieName);
			if(R.isNull(tokenValue)){
				r.setCode(ResultEncoding.R_ERR);
				r.setMsg("数据错误,请登录重试");
				return r;
			}
			
			String id=tokenValue.split("_")[0];
			String password_x=MD5.EncoderByMd5(admin.getPassword());
			String password_j=MD5.EncoderByMd5(password_s);
			if(loginMapper.updatePassword(password_x, id, password_j)==1){
				r.setMsg("修改成功");
				return r;
			}else{
				r.setMsg("修改失败,请确认旧密码是否正确");
				r.setCode(ResultEncoding.R_ERR);
				return r;
			}
		} catch (Exception e) {
			r.setCode(ResultEncoding.R_ERR);
			r.setMsg("系统异常,请登录重试");
			return r;
		}
		
	}
}
